package com.wzy.business.store.main.presenter.impl

import android.content.Context
import com.wangzhenyu.common.base.BasePreImpl
import com.wangzhenyu.common.base.bean.UserManager
import com.wangzhenyu.common.util.log.LogUtil
import com.wzy.business.base.ShopStatusConstants
import com.wzy.business.room.database.BusinessDatabase
import com.wzy.business.store.main.bean.ShopStatus
import com.wzy.business.store.main.dao.ShopStatusDao
import com.wzy.business.store.main.presenter.MainPresenter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainPresenterImpl(private val context: Context, private val view: MainPresenter.View) :
    BasePreImpl(view),
    MainPresenter {


    override fun requestMainInfoData() {

        mCoroutine.launch(Dispatchers.IO) {
            val shopStatusDao = BusinessDatabase.getInstance(context).getShopStatusDao()
            val loginInfo = UserManager.getLoginInfo()
            val shopStatus: ShopStatus

            if (loginInfo?.mobile != null) {
                val temp = shopStatusDao.queryShopStatusByPhone(loginInfo.mobile!!)
                shopStatus = if (temp.isEmpty()) {
                    shopStatusDao.addShopStatus(ShopStatus(loginInfo.mobile!!))
                    shopStatusDao.queryShopStatusByPhone(loginInfo.mobile!!)[0]
                } else {
                    temp[0]
                }
                loginInfo.shopStatus = shopStatus.shopStatus
                loginInfo.statusReason = shopStatus.statusReason
                loginInfo.openStatus = shopStatus.openStatus == 1
                loginInfo.showButton = shopStatus.showButton
                loginInfo.have_opentime = shopStatus.have_opentime == true
                loginInfo.have_shoplogo = shopStatus.have_shoplogo == true
                loginInfo.have_mobile = shopStatus.have_mobile == true
                UserManager.setLoginInfo(loginInfo)

                if (ShopStatusConstants.isAuthed(shopStatus.shopStatus)) {
                    //店铺已开

                } else {
                    withContext(Dispatchers.Main)
                    {
                        view.onMainDataSuccess(null, shopStatus)
                    }
                }
            } else {
                withContext(Dispatchers.Main)
                {
                    view.onMainInfoError(-1)
                }
            }


        }


        //                    val resp = MainRepository.apiService.getMainData().awaitHiResponse()
        //                    if (resp.isSuccess) {
        //                        view.onMainDataSuccess(resp.data, shopStatus)
        //                    } else {
        //                        view.onMainInfoError(resp.code)
        //                    }
        //
        //


    }

    override fun requestAccountSettingData() {

    }


}